class RobotApp {
    constructor() {
        // 绑定方法
        this.init = this.init.bind(this);
        this.initThreeJsScenes = this.initThreeJsScenes.bind(this);
        this.setupEventListeners = this.setupEventListeners.bind(this);
        this.initializeUIControls = this.initializeUIControls.bind(this);
        this.updateLayout = this.updateLayout.bind(this);

        // 保存视图状态
        this.viewStates = {
            world: { id: 'world-content', active: true },
            camera: { id: 'camera-content', active: false },
            lidar: { id: 'lidar-content', active: false },
            imu: { id: 'imu-content', active: false },
            map: { id: 'map-content', active: false },
            lineLaser: { id: 'line-laser-content', active: false },
            ir: { id: 'ir-content', active: false },
            cliff: { id: 'cliff-content', active: false }
        };
    }

    async init() {
        try {
            console.log("Loading config...");
            await configManager.loadConfig();

            console.log("Initializing Three.js scenes...");
            await this.initThreeJsScenes();

            console.log("Initializing point cloud processor...");
            const pointCloudProcessor = initPointCloudProcessor();
            if (!pointCloudProcessor) {
                throw new Error('Failed to initialize point cloud processor');
            }
            window.pointCloudProcessor = pointCloudProcessor;

            console.log("Initializing other components...");
            await this.initializeComponents();

            this.initializeUIControls();
            this.setupEventListeners();
            await this.initializeWebSocket();

        } catch (error) {
            console.error('Failed to initialize:', error);
            throw error;
        }
    }

    async initThreeJsScenes() {
        const worldContainer = document.getElementById('world-3d-container');
        if (!worldContainer) {
            throw new Error('3D container not found');
        }

        if (worldContainer.clientWidth === 0 || worldContainer.clientHeight === 0) {
            return new Promise(resolve => {
                setTimeout(() => this.initThreeJsScenes().then(resolve), 100);
            });
        }

        await worldScene.initScene(worldContainer);
        this.updateLayout();
    }

    async initializeComponents() {
        await initMissionControlPanel();
        await RobotMotionPanel.initialize().catch(error => {
            console.error('Failed to initialize motion panel:', error);
        });
        await ComponentStateTestPanel.initialize();

        // 添加系统信息面板的初始化
        await RobotSystemPanel.initialize().catch(error => {
            console.error('Failed to initialize system panel:', error);
        });
    }

    initializeUIControls() {
        this.initializeNavButtons();
        this.initializeCollapsePanel();
        this.initializeResizePanels();
    }

    // 在RobotApp类中更新initializeNavButtons方法
    initializeNavButtons() {
        const buttons = document.querySelectorAll('.nav-buttons .nav-button');

        // 设置初始状态
        buttons.forEach(button => {
            // 根据tooltip设置data-view属性
            const tooltip = button.getAttribute('data-tooltip');
            switch (tooltip) {
                case '世界地图':
                    button.setAttribute('data-view', 'world-content');
                    break;
                case '陀螺仪':
                    button.setAttribute('data-view', 'imu-content');
                    break;
                case '雷达调试':
                    button.setAttribute('data-view', 'lidar-content');
                    break;
                case '摄像头':
                    button.setAttribute('data-view', 'camera-content');
                    break;
                case '线激光点云':
                    button.setAttribute('data-view', 'line-laser-content');
                    break;
                case '红外传感器':
                    button.setAttribute('data-view', 'ir-content');
                    break;
                case '跌落传感器':
                    button.setAttribute('data-view', 'cliff-content');
                    break;
                case '性能监控':
                    button.setAttribute('data-view', 'performance-content');
                    break;
            }

            // 修复事件委托问题
            button.addEventListener('click', (e) => {
                const viewId = e.currentTarget.getAttribute('data-view');
                if (!viewId) return;

                const group = e.currentTarget.closest('.nav-buttons');
                if (!group) return;

                // 更新按钮状态
                group.querySelectorAll('.nav-button').forEach(btn => {
                    btn.classList.remove('active');
                });
                e.currentTarget.classList.add('active');

                // 更新内容面板
                const container = group.closest('.main-view');
                if (!container) return;

                container.querySelectorAll('.content-panel').forEach(panel => {
                    panel.classList.remove('active');
                });

                const targetPanel = document.getElementById(viewId);
                if (targetPanel) {
                    targetPanel.classList.add('active');
                    if (viewId === 'world-content') {
                        this.updateLayout();
                    }
                }

                // 更新视图状态
                Object.keys(this.viewStates).forEach(key => {
                    if (this.viewStates[key].id === viewId) {
                        this.viewStates[key].active = true;
                    } else if (container.contains(document.getElementById(this.viewStates[key].id))) {
                        this.viewStates[key].active = false;
                    }
                });
            });
        });
    }

    initializeCollapsePanel() {
        const leftPanel = document.querySelector('.left-panel-container');
        const collapseButton = leftPanel?.querySelector('.panel-collapse-button');

        if (!collapseButton || !leftPanel) return;

        collapseButton.addEventListener('click', () => {
            leftPanel.classList.toggle('collapsed');

            const icon = collapseButton.querySelector('[data-lucide="chevron-left"]');
            if (icon) {
                icon.style.transform = leftPanel.classList.contains('collapsed')
                    ? 'rotate(180deg)'
                    : '';
            }

            // 立即更新布局
            this.updateLayout();

            // 等待过渡动画完成后再次更新
            setTimeout(() => {
                this.updateLayout();
            }, 300);
        });
    }

    initializeResizePanels() {
        this.initializeVerticalResize();
        this.initializeHorizontalResize();
    }

    initializeVerticalResize() {
        const handle = document.querySelector('.resize-handle-vertical');
        const rightPanel = document.querySelector('.right-panel-container');

        if (!handle || !rightPanel) return;

        this.setupResizeHandler(handle, rightPanel, {
            direction: 'vertical',
            minSize: 320,
            maxSize: 600,
            getSizeFromEvent: (e, start, startSize) => {
                const delta = e.clientX - start.x;
                return startSize - delta;
            }
        });
    }

    initializeHorizontalResize() {
        const handle = document.querySelector('.resize-handle-horizontal');
        const logPanel = document.querySelector('.log-panel');

        if (!handle || !logPanel) return;

        this.setupResizeHandler(handle, logPanel, {
            direction: 'horizontal',
            minSize: 100,
            maxSize: window.innerHeight * 0.5,
            getSizeFromEvent: (e, start, startSize) => {
                const delta = start.y - e.clientY;
                return startSize + delta;
            }
        });
    }

    setupResizeHandler(handle, element, options) {
        let isResizing = false;
        let startPos = { x: 0, y: 0 };
        let startSize = 0;

        const startResize = (e) => {
            isResizing = true;
            startPos = { x: e.clientX, y: e.clientY };
            startSize = options.direction === 'vertical'
                ? element.offsetWidth
                : element.offsetHeight;

            handle.classList.add('active');
            document.body.style.cursor = options.direction === 'vertical' ? 'col-resize' : 'row-resize';
            document.body.style.userSelect = 'none';

            document.addEventListener('mousemove', onResize);
            document.addEventListener('mouseup', stopResize);
        };

        const onResize = (e) => {
            if (!isResizing) return;

            const newSize = Math.min(
                Math.max(options.minSize, options.getSizeFromEvent(e, startPos, startSize)),
                options.maxSize
            );

            if (options.direction === 'vertical') {
                element.style.width = `${newSize}px`;
                element.style.minWidth = `${newSize}px`;
            } else {
                element.style.height = `${newSize}px`;
            }

            // 立即触发更新，不用等动画帧
            if (window.worldScene) {
                window.worldScene.updateSceneSizes();
            }
            // 保持原有的更新
            this.updateLayout();
        };

        const stopResize = () => {
            isResizing = false;
            handle.classList.remove('active');
            document.body.style.cursor = '';
            document.body.style.userSelect = '';

            document.removeEventListener('mousemove', onResize);
            document.removeEventListener('mouseup', stopResize);

            this.updateLayout();
        };

        handle.addEventListener('mousedown', startResize);
    }

    updateLayout() {
        const container = document.getElementById('world-3d-container');
        if (!container || !window.threeObjects) return;

        requestAnimationFrame(() => {
            const { renderer, camera } = window.threeObjects;
            const rect = container.getBoundingClientRect();

            if (rect.width === 0 || rect.height === 0) return;

            camera.aspect = rect.width / rect.height;
            camera.updateProjectionMatrix();
            renderer.setSize(rect.width, rect.height, false);
            renderer.render(window.threeObjects.scene, camera);

            if (worldScene?.updateSceneSizes) {
                worldScene.updateSceneSizes();
            }
        });
    }

    setupEventListeners() {
        // 状态管理器监听
        window.robotStateManager.addListener(state => {
            if (window.robotControl) {
                window.robotControl.updateStatus({
                    battery: state.working.batteryLevel,
                    isWorking: state.working.status === 'working',
                    currentMode: state.working.mode
                });
            }
            robotComponentManager.updateComponentsState(state.components);
        });

        // 窗口大小变化监听
        window.addEventListener('resize', this.debounce(() => {
            this.updateLayout();
        }, 100));
    }

    async initializeWebSocket() {
        await webSocketHandler.init();

        webSocketHandler.addEventListener('connectionStatusChange', this.updateConnectionStatus);
        webSocketHandler.addEventListener('chassisMisc', this.handleChassisData);
    }

    updateConnectionStatus(connected) {
        const statusButton = document.getElementById('connection-status');
        if (statusButton) {
            statusButton.textContent = connected ? 'Connected' : 'Disconnected';
            statusButton.classList.toggle('disconnected', !connected);
        }
    }

    handleChassisData(data) {
        if (typeof handleChassisData === 'function') {
            handleChassisData(data);
        }
    }

    addLogMessage(message, level = 'info') {
        const logContent = document.querySelector('.log-content');
        if (!logContent) return;

        const timestamp = new Date().toISOString();
        const logEntry = document.createElement('div');
        logEntry.className = `log-entry ${level}`;
        logEntry.textContent = `${timestamp} [${level.toUpperCase()}] ${message}`;

        logContent.appendChild(logEntry);
        logContent.scrollTop = logContent.scrollHeight;
    }

    debounce(func, wait) {
        let timeout;
        return (...args) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => func(...args), wait);
        };
    }

    destroy() {
        // 清理事件监听
        window.removeEventListener('resize', this.handleResize);
        webSocketHandler.removeEventListener('connectionStatusChange', this.updateConnectionStatus);
        webSocketHandler.removeEventListener('chassisMisc', this.handleChassisData);
    }
}

// 创建应用实例
const robotApp = new RobotApp();

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    robotApp.init().catch(error => {
        console.error('Application initialization failed:', error);
    });
});

// 导出
if (typeof window !== 'undefined') {
    window.robotApp = robotApp;
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = { RobotApp, robotApp };
}